/**
 * @program school-bus-cloud
 * @description: AuthController
 * @author: mf
 * @create: 2020/11/03 13:30
 */

package com.eye.catcher.controller;

import com.eye.catcher.auth.param.AuthRequest;
import com.eye.catcher.common.RedisUtils;
import com.eye.catcher.constants.RedisConstants;
import com.eye.catcher.constants.SbCode;
import com.eye.catcher.jwt.JwtTokenUtil;
import com.eye.catcher.param.CommonBindingResult;
import com.eye.catcher.param.ResponseData;
import com.eye.catcher.param.ResponseUtil;
import com.eye.catcher.system.user.param.UserLoginRequst;
import com.eye.catcher.system.user.param.UserLoginResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;

@RestController
@Slf4j
public class AuthController {

    @Autowired
    private TSysDaUserController userController;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping(value = "${jwt.auth-path}")
    public ResponseData createAuthenticationToken(@Validated AuthRequest authRequest, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                log.error("参数：{}校验失败，原因：{}", fieldError.getField(), fieldError.getDefaultMessage());
            }
            return new ResponseUtil<>().setErrorMsg("用户参数设置错误:" + CommonBindingResult.getErrors(bindingResult));
        }
//        if(StringUtils.isEmpty(authRequest.getUserName())){
//            return new ResponseUtil<>().setErrorMsg("用户名不能为空");
//        }
//        if(StringUtils.isEmpty(authRequest.getPassword())){
//            return new ResponseUtil<>().setErrorMsg("密码不能为空");
//        }
        UserLoginRequst req = new UserLoginRequst();
        req.setUsername(authRequest.getUserName());
        req.setPassword(authRequest.getPassword());
        Object result = null;
        try {
            ResponseData login = userController.login(req);
            if (!login.isSuccess()) {
                return new ResponseUtil<>().setErrorMsg(login.getMessage());
            }
            result = login.getResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseUtil<>().setErrorMsg("eyeCatcher-system服务宕机，请联系管理员");
        }
        UserLoginResponse res = (UserLoginResponse) result;
        String status = res.getStatus();
        if (SbCode.DATA_DISABLE.getCode().equals(status)) {
            return new ResponseUtil<>().setErrorMsg("账号已被禁用");
        }
        if (!SbCode.SUCCESS.getCode().equals(res.getCode())) {
            return new ResponseUtil<>().setErrorMsg(res.getMsg());
        }
        UserLoginResponse res1 = new UserLoginResponse();
        String userId = res.getUserId();
        String loginName = res.getLoginName();
        String userName = res.getUserName();
        if (StringUtils.isNotBlank(userId)) {
            res1.setUserId(userId);
            res1.setUserName(userName);
            res1.setLoginName(loginName);
            res1.setRandomKey(jwtTokenUtil.getRandomKey());
            String token = jwtTokenUtil.generateToken(userId, res1.getRandomKey());
            res1.setToken(token);
            res1.setCode(res.getCode());
            res1.setMsg(res.getMsg());
            //每次登录清空用户信息，防止用户更改数据
//            redisUtils.del(RedisConstants.USER_INFO_EXPIRE.getKey()+userId);
            redisUtils.set(token, userId, RedisConstants.TOKEN_EXPIRE.getTime());
            return new ResponseUtil<>().setData(res1);
        } else {
            return new ResponseUtil<>().setErrorMsg("账号密码错误");
        }
    }
}
